package com.zzzzzz.content.comment;

import java.util.List;

import org.bson.types.ObjectId;
import org.springframework.stereotype.Repository;

import com.google.code.morphia.query.Query;
import com.zzzzzz.common.util.StringPool;
import com.zzzzzz.core.dao.morphia.BaseDao;

@Repository("commentDao")
public class CommentDaoImpl extends BaseDao implements CommentDao {
	@Override
	public void add(Comment comment) {
		db.save(comment);
	}

	@Override
	public void editStatus(String userId, String commentId, Integer status) {
		Query<Comment> query = db.createQuery(Comment.class);
		query.filter("_id", ObjectId.massageToObjectId(commentId))
			.filter("userId", userId);
		db.update(query, db.createUpdateOperations(Comment.class).set("status", status));
	}

	@Override
	public void edit(Comment comment) {
		Query<Comment> query = db.createQuery(Comment.class);
		query.filter("_id", ObjectId.massageToObjectId(comment.getCommentId()))
			.filter("userId", comment.getUserId());
		db.update(query, db.createUpdateOperations(Comment.class)
				.set("text", comment.getText())
				.set("updDt", comment.getUpdDt())
		);
	}

	@Override
	public long findCountByTopicId(String topicId) {
		Query<Comment> query = db.createQuery(Comment.class);
		query.filter("topicId", topicId).filter("status", 0);
		return db.getCount(query);
	}
	
	@Override
	public List<Comment> findByTopicId(String topicId) {
		Query<Comment> query = db.createQuery(Comment.class);
		query.filter("topicId", topicId).filter("status", 0);
		return query.asList();
	}
	
	@Override
	public List<Comment> findByTopicId(String topicId, int start, int offset, boolean ascending) {
		Query<Comment> query = db.createQuery(Comment.class);
		String condition = "addDt";
		if(!ascending) {
			condition = StringPool.DASH + condition;
		}
		query.filter("topicId", topicId).filter("status", 0).limit(offset).offset(start).order(condition);
		return query.asList();
	}
}
